import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';

import '../../../../core/utils/show_toast.dart';
import '../../../../data/controllers/sports_controller.dart';
import '../models/sport.dart';

part 'sports_state.dart';
part 'sports_event.dart';

class SportsCubit extends Bloc<SportsEvent, SportsState> {
  SportsCubit(SportsState initialState) : super(SportsInitial()){
    on<SportsInitialEvent>(_onInitialize);
    on<GetSportsEvent>(_onGetSports);
    on<SelectModeEvent>(_onChangeSelectMode);
    on<SelectSportEvent>(_onSelectSport);
  }

  static SportsCubit get(context) => BlocProvider.of(context);
  List<Sport> sports = [];
  List<Sport> selectedSports = [];
  bool selectMode = false;

  _onInitialize(
      SportsInitialEvent event,
      Emitter<SportsState> emit,
      )async {
    sports = [];
    emit(SportsLoading());
    await SportsController.getAllSports().catchError((e){
      emit(SportsError());
      return null;
    }).then((value){
      if(value != null && value.state) {
        add(SelectModeEvent(mode: false));
        sports = List<Sport>.generate(value.data.length, (index) => Sport.fromJson(value.data[index]));
        emit(SportsDone());
      }else if(value != null){
        showMessage(value.message);
        emit(SportsError());
      }else{
        if (kDebugMode) {
          print('value is null');
        }
      }
    });
  }


  _onGetSports(
      GetSportsEvent event,
      Emitter<SportsState> emit,
      )async{
    sports = [];
    emit(SportsLoading());
    await SportsController.getAllSports().catchError((e){
      emit(SportsError());
      return null;
    }).then((value){
      if(value != null && value.state) {
        sports = List<Sport>.generate(value.data.length, (index) => Sport.fromJson(value.data[index]));
        emit(SportsDone());
      }else if(value != null){
        showMessage(value.message);
        emit(SportsError());
      }else{
        if (kDebugMode) {
          print('value is null');
        }
      }
    });
  }


  _onChangeSelectMode(
      SelectModeEvent event,
      Emitter<SportsState> emit,
      )async{
    selectMode = event.mode;
    if(event.sport != null){
      selectedSports.add(event.sport!);
    }
    if(!event.mode){
      selectedSports.clear();
    }
    emit(SelectModeUpdate( mode: selectMode));
  }

  _onSelectSport(
      SelectSportEvent event,
      Emitter<SportsState> emit,
      )async{
    if(event.isSelected){
      selectedSports.add(event.sport);
    }else{
      selectedSports.remove(event.sport);
    }
    emit(SelectSport(sport: event.sport,isSelected: event.isSelected));
  }


  _onAddToGym(
      AddToGymEvent event,
      Emitter<SportsState> emit,
      )async{
    emit(AddSportToGymLoading(sport: event.sport));



  }

  Future onRefresh()async{
    add(SportsInitialEvent());
  }
}
